package com.sdp.th.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.th.cache.ThCleanCache;
import com.sdp.th.db.th_region.service.IThRegionService;
import com.sdp.th.entity.ThRegion;

/**
 * <p>
 * 区域信息 前端控制器
 * </p>
 *
 * @author zsp
 * @since 2025-04-12
 */
@RestController
@RequestMapping("/ThRegionController")
public class ThRegionController {
	
	@Autowired
	private IThRegionService iThRegionService;

	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private ThCleanCache thCleanCache;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iThRegionService, ThRegion.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody ThRegion tegion) {
		if(tegion==null) {
			return Result.error("区域信息为空");
		}

		if(StringUtils.isEmpty(tegion.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iThRegionService, ThRegion.class, new String[] {"regionNo","regionName"}, "keyId", tegion, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("区域编码和名称不能重复");
			}
			iThRegionService.save(tegion);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iThRegionService, ThRegion.class, new String[] {"regionNo","regionName"}, "keyId", null, tegion, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("区域编码和名称不能重复");
			}
			iThRegionService.updateById(tegion);
		}

		thCleanCache.cleanRegionCache();
		return Result.ok();
	}

}

